<template>
  <el-dialog
      v-model="showModal"
      title="用户登录"
      width="35%"
      :close-on-click-modal="false"
      :before-close="handleBeforeClose"
      @close="resetForm"
      class="login-dialog"
  >
    <el-row :gutter="20" class="login-container">
      <!-- 左侧二维码区域 -->
      <el-col :xs="24" :sm="8" class="qr-code-section">
        <div class="qr-content">
          <div class="qr-placeholder">
            <!-- 可替换为真实二维码图片 -->
            <i class="el-icon-mobile-phone" style="font-size: 64px; color: #999;"></i>
          </div>
          <div class="qr-text">
            <h3>扫码登录</h3>
            <p class="qr-subtitle">微信/QQ扫码登录</p>
            <p class="qr-tip">其他登录方式</p>
          </div>
        </div>
      </el-col>

      <!-- 右侧表单区域 -->
      <el-col :xs="24" :sm="16" class="form-section">
        <el-tabs v-model="activeTab" stretch class="login-tabs">
          <!-- 手机号登录 -->
          <el-tab-pane label="手机号登录" name="phone">
            <el-form ref="phoneFormRef" :model="phoneFormData" :rules="phoneRules" label-width="100px" class="login-form">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="phoneFormData.phone" placeholder="请输入手机号码" />
              </el-form-item>

              <el-form-item label="验证码" prop="code">
                <el-input v-model="phoneFormData.code" placeholder="请输入验证码" style="width: 60%; display: inline-block;" />
                <el-button
                    @click="sendPhoneVerificationCode"
                    :disabled="phoneSending"
                    style="margin-left: 10px;"
                    class="code-btn"
                >{{ phoneSendText }}</el-button>
              </el-form-item>
              <el-form-item class="terms-item">
                <el-checkbox v-model="agreedToTerms">
                  我已阅读并同意
                  <span class="terms-link" @click.stop="showTermsDialog = true">服务协议</span>
                </el-checkbox>
              </el-form-item>
              <el-form-item class="form-buttons">
                <el-button type="primary" @click="submitPhoneLogin" class="login-btn">登录</el-button>
                <el-button @click="resetPhoneForm" class="reset-btn">重置</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>

          <!-- 账号密码登录 -->
          <!-- 在模板部分修改账号密码登录的表单 -->
          <el-tab-pane label="账号密码登录" name="account">
            <el-form ref="accountFormRef" :model="accountFormData" :rules="accountRules" label-width="100px" class="login-form">
              <!-- 修改这里：用户名改为账号，支持多种输入 -->
              <el-form-item label="账号" prop="account">
                <el-input
                    v-model="accountFormData.account"
                    placeholder="请输入用户名/手机号/邮箱"
                />
              </el-form-item>

              <el-form-item label="密码" prop="password">
                <el-input
                    v-model="accountFormData.password"
                    type="password"
                    show-password
                    placeholder="请输入密码"
                />
              </el-form-item>
              <el-form-item class="terms-item">
                <el-checkbox v-model="agreedToTerms">
                  我已阅读并同意
                  <span class="terms-link" @click.stop="showTermsDialog = true">服务协议</span>
                </el-checkbox>
              </el-form-item>
              <el-form-item class="form-buttons">
                <el-button type="primary" @click="submitAccountLogin" class="login-btn">登录</el-button>
                <el-button @click="resetAccountForm" class="reset-btn">重置</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>

        </el-tabs>

        <!-- 底部链接 -->
        <div class="bottom-links">
          <el-link @click="$router.push('/login/forget')">忘记密码？</el-link>
          <el-link @click="switchToRegister">立即注册</el-link>
        </div>
      </el-col>
    </el-row>
  </el-dialog>

  <!-- 服务协议弹窗 -->
  <TermsDialog
      v-model="showTermsDialog"
      @agree="agreedToTerms = true"
  />
</template>

<script>
import TermsDialog from "@/views/terms/TermsDialog.vue";

export default {
  name: "BaseUserLogin",
  components: {TermsDialog},
  props: {
    modelValue: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      activeTab: "phone", // 默认手机号登录

      // 手机号登录数据
      phoneFormData: {
        phone: "",
        code: ""
      },
      phoneSending: false,
      phoneSendText: "获取验证码",
      agreedToTerms: false,
      showTermsDialog: false, // 控制服务协议弹窗显示

      phoneRules: {
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "验证码不能为空", trigger: "blur" }
        ]
      },

      // 账号密码登录数据
      // 账号密码登录数据
      accountFormData: {
        account: "", // 改为通用账号字段
        password: "",
        accountType: "username" // 添加账号类型标识
      },
      accountRules: {
        account: [
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              // 验证用户名格式（允许中文、字母、数字和下划线）
              const usernameRegex = /^[\u4E00-\u9FA5A-Za-z0-9_]{1,16}$/;
              // 验证手机号格式
              const phoneRegex = /^1[3-9]\d{9}$/;
              // 验证邮箱格式
              const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

              if (!value) {
                return callback(new Error("账号不能为空"));
              }

              // 优先检查手机号格式（最严格）
              if (phoneRegex.test(value)) {
                this.accountFormData.accountType = "phone";
              }
              // 其次检查邮箱格式
              else if (emailRegex.test(value)) {
                this.accountFormData.accountType = "email";
              }
              // 最后检查用户名格式
              else if (usernameRegex.test(value)) {
                this.accountFormData.accountType = "username";
              } else {
                return callback(new Error("请输入有效的用户名/手机号/邮箱"));
              }

              callback();
            },
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: "密码长度在6-20个字符", trigger: "blur" }
        ]
      }
    };
  },

  computed: {
    showModal: {
      get() {
        return this.modelValue;
      },
      set(value) {
        this.$emit("update:modelValue", value);
      }
    }
  },
  methods: {
    switchToRegister() {
      // 在 BaseUserLogin.vue 中
      this.$emit('update:modelValue', false); // 关闭自己
      this.$emit('open-register'); // 打开注册弹窗
    },
    handleLoginSuccess(data) {
      const userData = data.user;
      const token = data.token;

      if (!userData || !token) {
        console.error("登录失败：用户信息或Token缺失");
        this.$message.error("登录失败：用户信息或Token缺失");
        return;
      }

      localStorage.setItem("user", JSON.stringify(userData));
      localStorage.setItem("token", token);

      this.showModal = false;
      // 添加欢迎消息
      this.$message.success(`登录成功，欢迎${userData.username}！`);

      // 触发登录成功事件
      this.$emit("login-success", userData); // 传递用户数据给父组件

      // 如果用户类型为0，则打开新手指引
      if (userData.userType === 0) {
        this.$emit("open-guide"); // 新增事件
      } else {
        this.$router.push("/index");
      }
    },

    // 手机号登录提交
    submitPhoneLogin() {
      this.$refs.phoneFormRef.validate(async valid => {
        if (valid) {
          try {
            if (!this.agreedToTerms) {
              this.$message.warning("请先同意服务协议");
              return;
            }
            const response = await fetch(BASE_URL + "/api/v1/users/login", {
              method: "POST",
              headers: {
                "Content-Type": "application/json"
              },
              body: JSON.stringify(this.phoneFormData)
            });

            if (!response.ok) throw new Error("登录失败");

            const result = await response.json();
            // 在 submitPhoneLogin 中
            this.handleLoginSuccess(result.data);
          //  this.$emit("login-success", result.data); // 添加此行

            this.showModal = false;
            this.resetPhoneForm();

            this.$router.push("/index");
          } catch (error) {
            console.error(error);
            this.$message.error("登录失败，请检查信息");
          }
        }
      });
    },

    // 账号密码登录提交
// 修改账号密码登录提交方法
    submitAccountLogin() {
      this.$refs.accountFormRef.validate(async valid => {
        if (valid) {
          try {
            if (!this.agreedToTerms) {
              this.$message.warning("请先同意服务协议");
              return;
            }

            // 根据账号类型构建请求数据
            const requestData = {
              password: this.accountFormData.password
            };

            // 根据账号类型设置不同字段
            switch (this.accountFormData.accountType) {
              case "username":
                requestData.username = this.accountFormData.account;
                break;
              case "phone":
                requestData.phone = this.accountFormData.account;
                break;
              case "email":
                requestData.email = this.accountFormData.account;
                break;
            }

            const response = await fetch(BASE_URL + "/api/v1/users/login", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify(requestData)
            });

            if (!response.ok) throw new Error("登录失败");

            const result = await response.json();

            // 在 submitAccountLogin 中
            this.handleLoginSuccess(result.data);
         //   this.$emit("login-success", result.data); // 添加此行

            this.showModal = false;
            this.resetAccountForm();

            this.$router.push("/index");
          } catch (error) {
            console.error(error);
            this.$message.error("登录失败，请检查用户名或密码");
          }
        }
      });
    },

    // 发送手机验证码
    sendPhoneVerificationCode() {
      if (!this.phoneFormData.phone) {
        this.$message.warning("请先输入手机号");
        return;
      }

      this.phoneSending = true;
      let timeLeft = 60;
      this.phoneSendText = `${timeLeft}s`;

      const timer = setInterval(() => {
        if (timeLeft > 0) {
          timeLeft--;
          this.phoneSendText = `${timeLeft}s`;
        } else {
          clearInterval(timer);
          this.phoneSending = false;
          this.phoneSendText = "获取验证码";
        }
      }, 1000);

      // 实际开发中替换为真实发送验证码接口
      // 示例调用接口
      fetch(BASE_URL + "/api/v1/users/send-code", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ phone: this.phoneFormData.phone })
      }).catch(err => {
        clearInterval(timer);
        this.phoneSending = false;
        this.phoneSendText = "获取验证码";
        console.error(err);
        this.$message.error("验证码发送失败");
      });
    },

    resetPhoneForm() {
      this.$refs.phoneFormRef.resetFields();
    },
    resetAccountForm() {
      this.$refs.accountFormRef.resetFields();
    },
    resetForm() {
      this.resetPhoneForm();
      this.resetAccountForm();
    },
    handleBeforeClose(done) {
      this.$confirm("你确定退出登录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        done();
        this.resetForm();
      }).catch(() => {});
    }
  }
};
</script>

<style scoped lang="css">
.login-dialog {
  border-radius: 16px;
  overflow: hidden;

  .el-dialog__header {
    background: linear-gradient(135deg, #ff9800, #ff6d00);
    margin: 0;

    .el-dialog__title {
      color: white;
      font-weight: bold;
      font-size: 20px;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: white;
      }
    }
  }

  .el-dialog__body {
    padding: 0;
  }
}

.login-container {
  background-color: #fff;
  min-height: 400px;
  display: flex;
  flex-wrap: wrap;
}

.qr-code-section {
  background: linear-gradient(to bottom, #f9f9f9, #f0f0f0);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30px 20px;

  .qr-content {
    text-align: center;
    max-width: 280px;

    .qr-placeholder {
      width: 160px;
      height: 160px;
      background: #fff;
      border-radius: 12px;
      margin: 0 auto 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      border: 1px solid #eee;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
      }
    }

    .qr-text {
      h3 {
        font-size: 18px;
        color: #333;
        margin-bottom: 5px;
      }

      .qr-subtitle {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
      }

      .qr-tip {
        font-size: 12px;
        color: #999;
        margin-top: 15px;
      }
    }
  }
}

.form-section {
  padding: 25px;
  background-color: #fff;
  position: relative;

  .login-tabs {
    :deep(.el-tabs__nav) {
      width: 100%;
      display: flex;
    }

    :deep(.el-tabs__item) {
      flex: 1;
      text-align: center;
      font-size: 16px;
      font-weight: 500;
      padding: 0 15px;
      transition: all 0.3s;

      &:hover {
        color: #ff9800;
      }
    }

    :deep(.el-tabs__active-bar) {
      background-color: #ff9800;
      height: 3px;
    }

    :deep(.el-tabs__content) {
      padding: 20px 0;
    }
  }

  .login-form {
    .el-form-item {
      margin-bottom: 22px;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .el-input {
      border-radius: 10px;

      :deep(.el-input__inner) {
        border-radius: 10px;
        padding-left: 15px;
        height: 42px;
        line-height: 42px;
        border: 1px solid #e0e0e0;
        transition: all 0.3s;

        &:focus {
          border-color: #ff9800;
          box-shadow: 0 0 0 2px rgba(255, 152, 0, 0.2);
        }
      }
    }

    .code-btn {
      background-color: #f5f5f5;
      border-radius: 10px;
      color: #666;
      height: 42px;
      transition: all 0.3s;

      &:hover {
        background-color: #eee;
        color: #ff9800;
      }

      &:disabled {
        background-color: #f9f9f9;
        color: #ccc;
        cursor: not-allowed;
      }
    }

    .terms-item {
      margin-top: 15px;
      margin-bottom: 20px;

      .terms-link {
        color: #ff9800;
        cursor: pointer;
        text-decoration: none;
        transition: all 0.3s;

        &:hover {
          color: #ff6d00;
          text-decoration: underline;
        }
      }
    }

    .form-buttons {
      display: flex;
      justify-content: space-between;

      .login-btn, .reset-btn {
        flex: 1;
        height: 44px;
        border-radius: 10px;
        font-size: 16px;
        font-weight: 500;
        margin: 0 5px;
        transition: all 0.3s;
      }

      .login-btn {
        background: linear-gradient(to right, #ff9800, #ff6d00);
        border: none;
        color: white;

        &:hover {
          opacity: 0.9;
          transform: translateY(-2px);
          box-shadow: 0 4px 10px rgba(255, 109, 0, 0.3);
        }
      }

      .reset-btn {
        background-color: #f5f5f5;
        color: #666;
        border: 1px solid #e0e0e0;

        &:hover {
          background-color: #eee;
          color: #ff9800;
        }
      }
    }
  }

  .bottom-links {
    display: flex;
    justify-content: flex-end;
    padding: 15px 0 5px;
    margin-top: 10px;
    border-top: 1px solid #f0f0f0;

    .el-link {
      margin-left: 20px;
      font-size: 14px;
      color: #666;
      transition: all 0.3s;

      &:hover {
        color: #ff9800;
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 992px) {
  .login-dialog {
    width: 80% !important;
  }
}

@media (max-width: 768px) {
  .login-dialog {
    width: 90% !important;
    max-width: 95%;
  }

  .qr-code-section {
    padding: 20px 15px;
    border-right: none;
    border-bottom: 1px solid #eee;

    .qr-content {
      display: flex;
      align-items: center;
      max-width: 100%;

      .qr-placeholder {
        width: 100px;
        height: 100px;
        margin-right: 15px;
        margin-bottom: 0;
      }

      .qr-text {
        text-align: left;

        h3 {
          font-size: 16px;
        }

        .qr-subtitle {
          font-size: 13px;
        }

        .qr-tip {
          font-size: 11px;
        }
      }
    }
  }

  .form-section {
    padding: 20px 15px;

    .login-form {
      .form-buttons {
        flex-direction: column;

        .login-btn, .reset-btn {
          width: 100%;
          margin: 5px 0;
        }
      }
    }
  }
}

@media (max-width: 480px) {
  .login-dialog {
    width: 95% !important;
  }

  .qr-code-section {
    .qr-content {
      flex-direction: column;
      text-align: center;

      .qr-placeholder {
        margin-right: 0;
        margin-bottom: 15px;
      }

      .qr-text {
        text-align: center;
      }
    }
  }

  .form-section {
    .login-tabs {
      :deep(.el-tabs__item) {
        font-size: 14px;
        padding: 0 8px;
      }
    }

    .login-form {
      .el-form-item {
        margin-bottom: 18px;
      }

      .el-input {
        :deep(.el-input__inner) {
          height: 38px;
          line-height: 38px;
        }
      }

      .code-btn {
        height: 38px;
        font-size: 13px;
      }

      .form-buttons {
        .login-btn, .reset-btn {
          height: 40px;
          font-size: 15px;
        }
      }
    }

    .bottom-links {
      flex-direction: column;
      align-items: flex-end;

      .el-link {
        margin-left: 0;
        margin-top: 8px;

        &:first-child {
          margin-top: 0;
        }
      }
    }
  }
}
</style>
